<?php

namespace App\Http\Controllers;

use App\Models\Roles;
use Illuminate\Http\Request;

class RoleController extends Controller{

    /**
     * 列表
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function index(){
        try {
            $lists = Roles::get();
            return $this->returnJson(0,'',$lists);
        } catch (\Exception $e) {
            return $this->returnJson(1, $e->getMessage());
        }

    }


    /**
     * 更新/新增数据
     * @param $data 表单数据
     * @return bool
     */
    protected function update(Request $request){
        try {
            $data = $request->all();
            if(!isset($data['id'])){
                //重复
                $info = Roles::where('title',$data['title'])->first();
                if($info){
                    return $this->returnJson(1,'该角色已经存在，请勿重复添加');
                }
                Roles::create($data);
                return $this->returnJson(0, '新角色据成功，页面即将跳转...');
            }else{
                //先查后更
                $info = Roles::find($data['id']);
                if(empty($info)){
                    return $this->returnJson(1,'抱歉，数据不存在');
                }
                $info->update($data);
                return $this->returnJson(0, '更新角色成功，页面即将跳转...');
            }
        } catch (\Exception $e) {
            return $this->returnJson(1, $e->getMessage());
        }
    }

    /**
     * 删除
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     * @throws \Exception
     */
    public function destory(Request $request){
        try {
            $id = $request->get('id');
            Roles::destroy($id);
            return $this->returnJson(0);
        } catch (\Exception $e) {
            return $this->returnJson(1, $e->getMessage());
        }

    }








}